package org.jeecg.modules.inventoryShelfAdjust.controller;

import java.security.Security;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basicCompartment.entity.BasicCompartment;
import org.jeecg.modules.basicCompartment.service.IBasicCompartmentService;
import org.jeecg.modules.basicShelf.entity.BasicShelf;
import org.jeecg.modules.basicShelf.service.IBasicShelfService;
import org.jeecg.modules.inventoryShelfAdjust.entity.InventoryShelfAdjust;
import org.jeecg.modules.inventoryShelfAdjust.service.IInventoryShelfAdjustService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.reportLabel.entity.ReportLabel;
import org.jeecg.modules.reportLabel.service.IReportLabelService;
import org.jeecg.modules.system.util.ThreadPoolManager;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 理货表
 * @Author: jeecg-boot
 * @Date:   2024-01-16
 * @Version: V1.0
 */
@Api(tags="理货表")
@RestController
@RequestMapping("/inventoryShelfAdjust/inventoryShelfAdjust")
@Slf4j
public class InventoryShelfAdjustController extends JeecgController<InventoryShelfAdjust, IInventoryShelfAdjustService> {
	@Autowired
	private IInventoryShelfAdjustService inventoryShelfAdjustService;
	@Autowired
	private IReportLabelService reportLabelService;
	@Autowired
	private IBasicShelfService shelfService;
	@Autowired
	private IBasicCompartmentService compartmentService;
	@Autowired
	private ThreadPoolManager threadPoolManager;
	
	/**
	 * 分页列表查询
	 *
	 * @param inventoryShelfAdjust
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "理货表-分页列表查询")
	@ApiOperation(value="理货表-分页列表查询", notes="理货表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(InventoryShelfAdjust inventoryShelfAdjust,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<InventoryShelfAdjust> queryWrapper = QueryGenerator.initQueryWrapper(inventoryShelfAdjust, req.getParameterMap());
		Page<InventoryShelfAdjust> page = new Page<InventoryShelfAdjust>(pageNo, pageSize);
		IPage<InventoryShelfAdjust> pageList = inventoryShelfAdjustService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param inventoryShelfAdjust
	 * @return
	 */
	@AutoLog(value = "理货表-添加")
	@ApiOperation(value="理货表-添加", notes="理货表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody InventoryShelfAdjust inventoryShelfAdjust) {
		inventoryShelfAdjustService.save(inventoryShelfAdjust);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param inventoryShelfAdjust
	 * @return
	 */
	@AutoLog(value = "理货表-编辑")
	@ApiOperation(value="理货表-编辑", notes="理货表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody InventoryShelfAdjust inventoryShelfAdjust) {
		inventoryShelfAdjustService.updateById(inventoryShelfAdjust);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "理货表-通过id删除")
	@ApiOperation(value="理货表-通过id删除", notes="理货表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		inventoryShelfAdjustService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "理货表-批量删除")
	@ApiOperation(value="理货表-批量删除", notes="理货表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.inventoryShelfAdjustService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "理货表-通过id查询")
	@ApiOperation(value="理货表-通过id查询", notes="理货表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		InventoryShelfAdjust inventoryShelfAdjust = inventoryShelfAdjustService.getById(id);
		if(inventoryShelfAdjust==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(inventoryShelfAdjust);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param inventoryShelfAdjust
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, InventoryShelfAdjust inventoryShelfAdjust) {
        return super.exportXls(request, inventoryShelfAdjust, InventoryShelfAdjust.class, "理货表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, InventoryShelfAdjust.class);
    }

	 /**
	  * 理货操作
	  */
	 @AutoLog(value = "理货表-理货操作")
	 @ApiOperation(value="理货表-理货操作", notes="理货表-理货操作")
	 @PostMapping(value = "/tallyOperation")
	 public Result<?> tallyOperation(@RequestParam(name="barCode",required=true) String barCode, @RequestParam(name="compartmentCode",required=true) String compartmentCode) {

		 LambdaQueryWrapper<ReportLabel> reportLabelLqw = Wrappers.lambdaQuery(ReportLabel.class);
		 reportLabelLqw.eq(ReportLabel::getBarCode, barCode);
		 List<ReportLabel> labels = reportLabelService.list(reportLabelLqw);
		 if (labels == null || labels.isEmpty()){
			 reportLabelLqw.clear();
			 reportLabelLqw.eq(ReportLabel::getLabelNumber, barCode);
			 labels = reportLabelService.list(reportLabelLqw);
			 if (labels == null || labels.isEmpty()){
				 return Result.error("货品标签识别异常，请核实后再重新扫码！");
			 }
		 }
		 if (labels.stream().anyMatch(label -> 5 != label.getStatus())){
			 return Result.error("货品在库信息查询为空，请核实后再重新扫码！");
		 }
		 /*if (compartmentCode.length()<=8){
			 return Result.error("货位标签识别异常，请核实后再重新扫码！");
		 }*/
		 if (labels.stream().anyMatch(label -> compartmentCode.equals(label.getCompartmentCode()))) {
			 return Result.error("新货位码与货品存放货位码一致，请核实后再重新扫码！");
		 }
		 LambdaQueryWrapper<BasicCompartment> compartmentLqw = Wrappers.lambdaQuery(BasicCompartment.class);
		 compartmentLqw.eq(BasicCompartment::getCompartmentCode, compartmentCode);
		 BasicCompartment compartment = compartmentService.getOne(compartmentLqw);
		 if (Objects.isNull(compartment)){
			 return Result.error("货位标签识别异常，请核实后再重新扫码！");
		 }
		 // 更新标签表货位信息
		 String shelfCode = compartmentCode.substring(0, 3);
		 for (ReportLabel label : labels){
			 label.setShelfCode(shelfCode);
			 label.setCompartmentCode(compartmentCode);
		 }
		 reportLabelService.updateBatchById(labels);
		 List<ReportLabel> finalLabels = labels;
		 Runnable task = () -> {
			 try {
				 // 添加理货表记录
				 addAdjust(compartmentCode, finalLabels, shelfCode);
			 } catch (Exception e) {
				 log.error("线程池调用【InventoryShelfAdjustController.tallyOperation】方法出现异常", e);
			 }
		 };
		 threadPoolManager.executeTask(task);

		 return Result.OK("操作成功", null);
	 }

	 private void addAdjust(String compartmentCode, List<ReportLabel> labels, String shelfCode) {
		 List<InventoryShelfAdjust> list = new LinkedList<>();
		 LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 for (ReportLabel reportLabel : labels){
			 InventoryShelfAdjust inventoryShelfAdjust = new InventoryShelfAdjust();
			 inventoryShelfAdjust.setSysOrgCode(reportLabel.getSysOrgCode());
			 inventoryShelfAdjust.setSkuCode(reportLabel.getSkuCode1());
			 inventoryShelfAdjust.setStatus(1);//已完成
			 inventoryShelfAdjust.setOldShelfCode(reportLabel.getShelfCode());
			 inventoryShelfAdjust.setOldCompartmentCode(reportLabel.getCompartmentCode());
			 inventoryShelfAdjust.setNewShelfCode(shelfCode);
			 inventoryShelfAdjust.setNewCompartmentCode(compartmentCode);
			 inventoryShelfAdjust.setFinishMan(user.getRealname());
			 inventoryShelfAdjust.setFinishTime(new Date());
			 inventoryShelfAdjust.setInOrderType(reportLabel.getInOrderType());
			 inventoryShelfAdjust.setLabelNumber(reportLabel.getLabelNumber());
			 inventoryShelfAdjust.setBarCode(reportLabel.getBarCode());
			 inventoryShelfAdjust.setCustomerCode(reportLabel.getCustomerCode());
			 list.add(inventoryShelfAdjust);
		 }
		 inventoryShelfAdjustService.saveBatch(list);
	 }

 }
